const { createStatementData } = require('./createStatementData_v12.js')
// 引用方式：CommonJS
const invoices = require("../asset/invoices.json")
const plays = require("../asset/plays.json")


/**
 * 核心程序1：调用纯文本格式的账单计算函数
 * @param {*} invoice 
 * @param {*} plays 
 * @returns 
 */
function statement(invoice, plays) {
  return renderPlainText(createStatementData(invoice, plays));
}

/**
 * 核心程序2：调用 HTML 格式的账单计算函数
 * @param {*} invoice 
 * @param {*} plays 
 * @returns 
 */
function htmlStatement(invoice, plays) {
  return renderHtml(createStatementData(invoice, plays));
}

/**
 * 打印账单详情(纯文本格式)
 * @param {*} data 
 * @returns 
 */
function renderPlainText(data) {
  let result = `Statement for ${data.customer}\n`;
  for (let perf of data.performances) {
    result += ` ${perf.play.name}: ${usd(perf.amount)} (${perf.audience} seats)\n`;
  }
  result += `Amount owed is ${usd(data.totalAmount)}\n`;
  result += `You earned ${data.totalVolumeCredits} credits\n`;
  return result;
}

/**
 * 打印账单详情(HTML 格式)
 * @param {*} data 
 * @returns 
 */
function renderHtml(data){
  let result = `<h1>Statement for ${data.customer}</h1>\n`;
  result += "<table>\n"
  result += "<tr><th>play</th><th>seats</th><th>cost</th></tr>\n"
  for (let perf of data.performances) {
    result += ` <tr><td>${perf.play.name}</td><td>${perf.audience}</td>`;
    result += ` <td>${usd(perf.amount)}</td></tr>\n`;
  }
  result += "</tr>\n"
  result += `<p>Amount owed is <em>${usd(data.totalAmount)}</em></p>\n`;
  result += `<p>You earned <em>${data.totalVolumeCredits}</em> credits</p>\n`;
  return result;

}


/**
 * 将数字格式化为 货币 & 将美分转换为美元（除以100）
 * @param {*} aNumber 
 */
function usd(aNumber) {
  return new Intl.NumberFormat("en-US",
    {
      style: "currency", currency: "USD",
      minimumFractionDigits: 2
    }).format(aNumber / 100);
}




// 调用
let invoice = invoices[0];
res = statement(invoice, plays);
// res = htmlStatement(invoice, plays);
console.log(res);
